# @file    : call_test
# @time    : 2025/4/2
# @author  : yongpeng.yao
# @desc    :
import json
import os
import time

from dashscope import Assistants, Threads, Runs, Messages
from dotenv import load_dotenv


def get_encouragement(name, mood):
    # 基础鼓励消息
    messages_ = {
        'happy': '继续保持积极的心态，做得好！',
        'sad': '记住，即使在最黑暗的时候，也有阳光在等着你。',
        'tired': '你做的足够好，现在是时候休息一下了。',
        'stressed': '深呼吸，一切都会好起来。'
    }
    message_ = messages_.get(mood.lower(), f'{name}，请输入正确的心情。')
    return f'亲爱的{name}，{message_}'


load_dotenv()
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_encouragement",
            "description": "根据用户的心情，返回一个鼓励用户的消息。",
            "parameters": {
                "type": "object",
                "properties": {
                    "name": {
                        "type": "string",
                        "description": "用户的名字。"
                    },
                    "mood": {
                        "type": "string",
                        "description": "用户的心情，可以是 'happy'、'sad'、'tired' 或 'stressed'。"
                    }
                }
            },
            "required": ["mood"]
        }
    }
]

assistant = Assistants.create(
    name='简单鼓励助手',
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    instructions='你是一个很会鼓励人的助手。',
    tools=tools,
    model='qwen-max'
)
thread = Threads.create()
print(thread)

message = Messages.create(
    thread_id=thread.id,
    role='user',
    content='你好，请鼓励一下考试前有点紧张的小雪吧！'
)
print(message)

run = Runs.create(
    assistant_id=assistant.id,
    thread_id=thread.id,
)


def poll_run_status(thread_id, run_id, interval=5):
    n = 0
    while True:
        n += 1
        run_ = Runs.retrieve(run_id=run_id, thread_id=thread_id)
        print(f'Run的第{n} 次状态为：\n{run_}')
        if run_.status in ('requires_action', 'completed', 'failed'):
            return run_
        time.sleep(interval)


run = poll_run_status(thread_id=thread.id, run_id=run.id)


def get_function_details(run_):
    print(run_)
    func_list_ = []
    for call in run_.required_action.submit_tool_outputs.tool_calls:
        name, args, func_id = call.function.name, call.function.arguments, call.id
        func_list_.append({'name': name, 'args': args, 'func_id': func_id})
    return func_list_


func_list = get_function_details(run)


def submit_tool_outputs(run_, thread_, func_list_):
    tool_outputs = []
    for func in func_list_:
        func_id = func['func_id']
        func_name = func['name']
        func_args = json.loads(func['args'])
        print(f'正在调用函数：{func_name}')
        func_result = eval(f'{func_name}(**{func_args})')
        print(f'函数{func_name}的返回结果为：{func_result}')
        tool_outputs.append({
            'tool_call_id': func_id,
            'output': func_result
        })
    Runs.submit_tool_outputs(
        run_id=run_.id,
        thread_id=thread_.id,
        tool_outputs=tool_outputs
    )
    return run_


run = submit_tool_outputs(run, thread, func_list)
print(run)

run = poll_run_status(thread_id=thread.id, run_id=run.id)
print(run)

messages = Messages.list(thread_id=thread.id)

for message in messages.data:
    if message.role == 'assistant':
        print(f'最终的回复为：\n{message.content}')
